using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace SynoManager
{
    /// <summary>
    /// Static class that provides two methods to safely encrypt passwords
    /// </summary>
    public static class PasswordHelper
    {
        static byte[] additionalEntropy = { 3, 1, 3, 3, 7 }; // leet!

        /// <summary>
        /// Encrypt a string.
        /// </summary>
        /// <param name="password">String to encrypt.</param>
        /// <returns>Encrypted string.</returns>
        /// <seealso cref="Unprotect(string)"/>
        public static string Protect(string password)
        {
            byte[] data = Encoding.Default.GetBytes(password);
            byte[] encryptedData = ProtectedData.Protect(data, additionalEntropy, DataProtectionScope.CurrentUser);
            return Encoding.Default.GetString(encryptedData);
        }

        /// <summary>
        /// Decrypt a string.
        /// </summary>
        /// <param name="password">Encrypted string.</param>
        /// <returns>Decrypted string.</returns>
        /// <seealso cref="Protect(string)"/>
        public static string Unprotect(string password)
        {
            if (String.IsNullOrEmpty(password))
                return password;

            byte[] encryptedData = Encoding.Default.GetBytes(password);
            byte[] data = ProtectedData.Unprotect(encryptedData, additionalEntropy, DataProtectionScope.CurrentUser);
            return Encoding.Default.GetString(data);
        }
    }
}
